<template>
  <el-container>
    <el-header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商家中心</el-breadcrumb-item>
        <el-breadcrumb-item>商家信息</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>
    <el-main>
      <el-card>
        <el-row>
          <el-col :span="3">
            <div class="block">
              <el-avatar shape="square" :size="90" :src="merchantInfo.icon"></el-avatar>
            </div>
          </el-col>
          <el-col :span="19">
            <div>
              <span class="nickname">{{merchantInfo.nickname}}</span>
            </div>
            <div class="detail">
              <span>{{merchantInfo.detail}}</span>
            </div>
          </el-col>
        </el-row>
        <el-tabs type="border-card" @tab-click="tabClick">
          <el-tab-pane label="商家信息">
            <div class="form-box">
              <el-form label-width="100px" label-position="left">
                <el-form-item label="用户名">
                  {{merchantInfo.username}}
                </el-form-item>
                <el-form-item label="商家名">
                  {{merchantInfo.nickname}}
                </el-form-item>
                <el-form-item label="商家地址">
                  {{merchantInfo.address}}
                </el-form-item>
                <el-form-item label="联系电话">
                  {{merchantInfo.phone}}
                </el-form-item>
                <el-form-item label="邮箱">
                  {{merchantInfo.email}}
                </el-form-item>
                <el-form-item label="商家描述">
                  {{merchantInfo.detail}}
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="修改信息">
            <div class="form-box">
              <el-form label-width="100px" :model="updateForm" :rules="updateFormRules" ref="updateFormRef" label-position="left">
                <el-form-item label="用户名" prop="rname">
                  <el-input v-model="updateForm.username"></el-input>
                </el-form-item>
                <el-form-item label="商家名" prop="rnickname">
                  <el-input v-model="updateForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="商家地址" prop="address">
                  <el-input v-model="updateForm.address"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="updateForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="updateForm.email"></el-input>
                </el-form-item>
                <el-form-item label="商家描述" prop="detail">
                  <el-input type="textarea" v-model="updateForm.detail"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateMerchantInfo">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="修改密码">
            <div class="form-box">
              <el-form label-width="100px" :model="passForm" :rules="passFormRules" ref="passFormRef" label-position="left">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input type="password" v-model="passForm.oldPassword"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                  <el-input type="password" v-model="passForm.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                  <el-input type="password" v-model="passForm.checkPassword"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword">确认修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="上传图片">
            <el-alert title="可上传头像、厨房图片和食材采购发票图片" type="info" :closable="false"></el-alert>
            <div class="upload-box">
              <span>上传商家头像</span>
              <el-upload
                class="upload-demo"
                drag
                :action="uploadAction"
                multiple
                :on-success="handleIconSuccess"
                :before-upload="beforeUpload"
                :data="this.iconData">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将头像照片拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2MB</div>
              </el-upload>
            </div>
            <div class="upload-box">
              <span>上传厨房照片</span>
              <el-upload
                class="upload-demo"
                drag
                :action="uploadAction"
                multiple
                :on-success="handleKPictureSuccess"
                :before-upload="beforeUpload"
                :data="this.kPictureData">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将厨房照片拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2MB</div>
              </el-upload>
            </div>
            <div class="upload-box">
              <span>上传采购食材发票照片</span>
              <el-upload
                class="upload-demo"
                drag
                :action="uploadAction"
                multiple
                :on-success="handleCPictureSuccess"
                :before-upload="beforeUpload"
                :data="this.cPictureData">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将采购食材发票照片拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过2MB</div>
              </el-upload>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: 'MerchantInfo',
  data () {
    const checkSpace = (rule, value, callback) => {
      const regSpace = /\s/
      if (!regSpace.test(value)) {
        return callback()
      }
      callback(new Error('不能有空格'))
    }
    // 确认密码的验证
    const checkPassword = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请再次输入密码'))
      }
      if (value === this.passForm.password) {
        return callback()
      }
      callback(new Error('两次输入的密码不一致'))
    }
    // 手机号的验证规则
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^([1][3,4,5,6,7,8,9])\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    // 邮箱的验证规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱地址'))
    }
    const checkOldPassword = (rule, value, callback) => {
      if (value !== this.oldPassword) {
        return callback(new Error('旧密码错误'))
      }
      callback()
    }
    const checkNewPassword = (rule, value, callback) => {
      if (value === this.oldPassword) {
        return callback(new Error('新密码不能跟旧密码一样'))
      }
      callback()
    }
    return {
      merchantInfo: {
        username: '',
        nickname: '',
        detail: '',
        phone: '',
        email: '',
        address: '',
        icon: '',
        kpicture: '',
        cpicture: ''
      },
      updateForm: {
        rid: window.sessionStorage.getItem('rid'),
        username: '',
        nickname: '',
        detail: '',
        phone: '',
        email: '',
        address: ''
      },
      oldPassword: '',
      passForm: {
        rid: window.sessionStorage.getItem('rid'),
        oldPassword: '',
        password: '',
        checkPassword: ''
      },
      passFormRules: {
        oldPassword: [
          {
            required: true,
            message: '请输入旧密码',
            trigger: 'blur'
          },
          {
            validator: checkOldPassword,
            trigger: 'submit'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '请输入6~20个字符',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          },
          {
            validator: checkNewPassword,
            trigger: 'submit'
          }
        ],
        checkPassword: [
          {
            required: true,
            validator: checkPassword,
            trigger: 'blur'
          }
        ]
      },
      updateFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '请输入3~20个字符',
            triggers: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入商家名',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入商家地址',
            trigger: 'blur'
          },
          {
            validator: checkSpace,
            trigger: 'blur'
          }
        ]
      },
      imageBaseUrl: this.$axios.defaults.baseURL + 'static/image/',
      uploadAction: this.$axios.defaults.baseURL + '/restaurant/upload',
      iconData: {
        rid: window.sessionStorage.getItem('rid'),
        imageType: 'icon'
      },
      kPictureData: {
        rid: window.sessionStorage.getItem('rid'),
        imageType: 'kpicture'
      },
      cPictureData: {
        rid: window.sessionStorage.getItem('rid'),
        imageType: 'cpicture'
      }
    }
  },
  created () {
    this.getMerchantInfo()
  },
  methods: {
    getMerchantInfo () {
      this.merchantInfo.username = window.sessionStorage.getItem('rname')
      this.merchantInfo.nickname = window.sessionStorage.getItem('rnickname')
      this.merchantInfo.detail = window.sessionStorage.getItem('detail')
      this.merchantInfo.phone = window.sessionStorage.getItem('phone')
      this.merchantInfo.email = window.sessionStorage.getItem('email')
      this.merchantInfo.address = window.sessionStorage.getItem('address')
      if (window.sessionStorage.getItem('icon') !== null && window.sessionStorage.getItem('icon') !== '') {
        this.merchantInfo.icon = this.imageBaseUrl + window.sessionStorage.getItem('icon') + '.jpg'
      }
      if (window.sessionStorage.getItem('kpicture') !== null && window.sessionStorage.getItem('kpicture') !== '') {
        this.merchantInfo.kpicture = this.imageBaseUrl + window.sessionStorage.getItem('kpicture') + '.jpg'
      }
      if (window.sessionStorage.getItem('cpicture') !== null && window.sessionStorage.getItem('cpicture') !== '') {
        this.merchantInfo.cpicture = this.imageBaseUrl + window.sessionStorage.getItem('cpicture') + '.jpg'
      }
    },
    tabClick () {
      this.$refs.updateFormRef.resetFields()
      this.$refs.passFormRef.resetFields()
      this.updateForm.username = this.merchantInfo.username
      this.updateForm.nickname = this.merchantInfo.nickname
      this.updateForm.detail = this.merchantInfo.detail
      this.updateForm.phone = this.merchantInfo.phone
      this.updateForm.email = this.merchantInfo.email
      this.updateForm.address = this.merchantInfo.address
    },
    updateMerchantInfo () {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$axios.post('/restaurant/update', this.updateForm)
        if (res.status !== 2000) {
          return this.$message.error('修改信息失败')
        }
        window.sessionStorage.setItem('rname', this.updateForm.username)
        window.sessionStorage.setItem('address', this.updateForm.address)
        window.sessionStorage.setItem('detail', this.updateForm.detail)
        window.sessionStorage.setItem('email', this.updateForm.email)
        window.sessionStorage.setItem('phone', this.updateForm.phone)
        window.sessionStorage.setItem('rnickname', this.updateForm.nickname)
        this.getMerchantInfo()
        this.$message.success('保存成功')
      })
    },
    async updatePassword () {
      const rid = { rid: window.sessionStorage.getItem('rid') }
      const { data: res } = await this.$axios.get('/restaurant/queryByID', { params: rid })
      if (res.status !== 2000) {
        return this.$message.error('修改密码失败，请稍后重试')
      }
      this.oldPassword = res.data.restaurant.rpassword
      await this.$refs.passFormRef.validate(async (valid) => {
        if ((!valid)) {
          return false
        }
        const { data: res } = await this.$axios.post('/restaurant/update', this.passForm)
        if (res.status !== 2000) {
          return this.$message.error('修改密码失败')
        }
        this.$message.success('修改成功,请重新登录')
        window.sessionStorage.clear()
        await this.$router.push('/login')
      })
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB')
      }
      return isJPG && isLt2M
    },
    handleIconSuccess (res) {
      window.sessionStorage.setItem('icon', res.data.restaurant.icon)
      this.getMerchantInfo()
    },
    handleKPictureSuccess (res) {
      window.sessionStorage.setItem('kpicture', res.data.restaurant.kpicture)
      this.getMerchantInfo()
    },
    handleCPictureSuccess (res) {
      window.sessionStorage.setItem('cpicture', res.data.restaurant.cpicture)
      this.getMerchantInfo()
    }
  }
}
</script>

<style scoped>
.nickname {
  font-size: 25px;
}
.detail {
  margin-top: 20px;
}
.el-header {
  height: 20px!important;
}
.el-tabs {
  margin-top: 20px;
}
.form-box {
  margin-top: 30px;
  width: 500px;
}
.upload-box {
  margin-top: 30px;
  margin-right: 50px;
  width: 360px;
  height: 250px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
